package com.baize.glinkad.utils.net;
import android.content.Context;

import com.baize.glinkad.bean.ADType;
import com.baize.glinkad.bean.Action;
import com.baize.glinkad.utils.ADLogHelper;
import com.baize.glinkad.utils.ADTool;
import com.baize.glinkad.utils.CryptUtil;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ADReport {

    private static final int TIMEOUT_IN_MILLIONS = 25000;

    private static ExecutorService sExecutorService;


    public static int POOL_SIZE = 8;

    static {
        sExecutorService = Executors.newFixedThreadPool(POOL_SIZE);
    }

    public static  void report(Context context,String appid, String posId, ADType aDType, Action action){
        JSONObject jsonObject = new JSONObject();
        try{
            jsonObject.put("appid",appid);
            jsonObject.put("sources",posId);
            jsonObject.put("adType",aDType);
            jsonObject.put("eventNode",action);
            jsonObject.put("channelCode", ADTool.getCurrChannel(context));
//            jsonObject.put("imei","");
            jsonObject.put("platform","1");
//            jsonObject.put("oaid","");
            sendPost("https://sdk.baizehudong.com/api/glink/report", jsonObject.toString(), new Callback() {
//            sendPost("http://192.168.0.64:17992/api/glink/report", jsonObject.toString(), new Callback() {
                @Override
                public void ok(String result) {

                }

                @Override
                public void fail() {

                }
            });
        }catch (Exception e){
            ADLogHelper.error(e.toString());
        }
    }

    private static void sendPost(final String url, final String param, final Callback callback){
        sExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                doPost(url, param , callback) ;
            }
        });
    }

    private static void doPost(String postUrl, String strReqJsonStr,Callback callback){
        String resp = null;
        HttpURLConnection httpURLConnection = null;
        BufferedReader in = null;
        PrintWriter out = null;
        String[] ary = postUrl.split("api");
        String title = ary.length==2?ary[1]:ary[0];
        try {
            URL url = new URL(postUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            out = new PrintWriter(httpURLConnection.getOutputStream());
            if(strReqJsonStr != null){
                JSONObject data = new JSONObject();
                data.put("data", CryptUtil.encode(strReqJsonStr));
                strReqJsonStr = data.toString();
                out.write(strReqJsonStr);
            }
            out.flush();
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer content = new StringBuffer();
                String tempStr = null;
                in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
                resp = content.toString();
                ADLogHelper.info(title +"请求参数:["+strReqJsonStr + "] 请求结果 : "+resp);
                callback.ok(resp);
            }else {
                callback.fail();
            }
        } catch (Exception e) {
            ADLogHelper.info(title +"发送请求异常,请求参数:"+strReqJsonStr);
            callback.fail();
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            } catch (Exception e) {
            }
        }
    }

    public interface Callback{
        void ok(String result) ;
        void fail();
    }

}

